/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exm;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Random;
import exm.question.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author ANTONIO
 */
public class Selection {
    private int n;  //number of questions
    private int m;  //number of topics
    
    public Selection(int numQuestions, int numTopics){
        n = numQuestions;
        m = numTopics;
    }
    
    public questionReturned questions(ArrayList p){
        //Pre: size(p) = m
        boolean right = false;
        Random random = new Random();
        int quest;
        ArrayList list = new ArrayList(0);
        ConnectionDB conDB = new ConnectionDB();
        Connection con = conDB.createConnection(); //Creating connection
        try {
            Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
            ResultSet rs = null;             
            list = new ArrayList(n);
            int k;
            int i=0;
            for(int j = 1; j<=m; j++){ //for each topic
                k = 0;                    
                String top = this.topics(j);  
                String query = "SELECT QNO,TOPIC,SUBTOPIC,WT,PTS FROM SAVEQA WHERE TOPIC = '"+top+"'"; 
                rs = st.executeQuery(query); 
                int count = 0; //count will store the number of rows selected
                while (rs.next())
                    count++; 
                int need = (Integer) p.get(j-1);
                if(need>count){
                    questionReturned q = new questionReturned (list,false);
                    return q;
                }else{
                    while (k!=p.get(j-1)){ 
                        rs.first();
                        quest = random.nextInt();          
                        quest = quest % (count-1);                         
                        quest = Math.abs(quest);
                        for(int aux=0; aux<quest; aux++)
                            rs.next();
                        
                        question q = new question(rs.getInt("qno"),rs.getString("topic"),rs.getString("subtopic"),rs.getString("wt"),rs.getInt("pts"));
                        //Añadirla a la lista                         
                        if((!this.isQuestion(list, q.getNumQuestion()))&&(!this.isSubtopic(list, rs.getString("topic"), rs.getString("subtopic")))){
                        //if((!this.isQuestion(list, q.getNumQuestion()))&&(!this.isSubtopic(list,q.getTopic(),q.getSubtopic()))){
                            i++;                        
                            k++;                        
                            list.add(q);
                        }  
                    }
                }
            } 
            int count2;
            String query = "SELECT QNO,TOPIC,SUBTOPIC,WT,PTS FROM SAVEQA"; 
            rs = st.executeQuery(query);
            count2=0;
            while (rs.next())
                count2++;                
            Random random2 =new Random();
            random2.setSeed(random2.nextInt()%m);
            while(i<n){                    
                rs.first();                    
                quest = random2.nextInt();
                quest = quest % (count2-1);                         
                quest = Math.abs(quest);
                for(int aux=0; aux<quest; aux++)
                    rs.next();
                     
                question q = new question(rs.getInt("qno"),rs.getString("topic"),rs.getString("subtopic"),rs.getString("wt"),rs.getInt("pts"));                    
                if((!this.isQuestion(list, q.getNumQuestion()))&&(!this.isSubtopic(list, rs.getString("topic"), rs.getString("subtopic")))){
                //if((!this.isQuestion(list, q.getNumQuestion()))&&(!this.isSubtopic(list,q.getTopic(),q.getSubtopic()))){
                    i++;                                              
                    list.add(q);
                }                       
            }            
            st.close();
            rs.close();
            right = true;
            list = this.changeWeight(con,list);
            
            int counter = 0;
            for(int j=0;j<list.size();j++)
                counter+=((question) list.get(j)).getWeightInt();
            float averageCounter = (float)counter/(float)list.size();
            
            System.out.print("FINAL: ");
            System.out.println(averageCounter);
            
            conDB.closeConnection(con);
        } catch (SQLException ex) {
            System.out.println("Impossible connection with database");
        } finally {        
            questionReturned q = new questionReturned (list,right);
            return q;
        }
    }
    
    public ArrayList changeWeight(Connection con, ArrayList list){
        Random random = new Random();
        ReadInitFile r = new ReadInitFile();
        
        float lowerDif = Float.valueOf(r.readLine(8));
        float harderDif = Float.valueOf(r.readLine(10));
            
        int counter=0;
        for(int j=0;j<list.size();j++){
            counter+=((question) list.get(j)).getWeightInt();
        }
        Statement st = null;
        try {
            //Counter = total difficulty
            st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
            float averageCounter = ((float)counter/(float)list.size());
            boolean found;
            int count;
            while(!((lowerDif<=averageCounter)&&(harderDif>=averageCounter))){
                found = false;
                if(lowerDif>averageCounter){ 
                    int numQ = random.nextInt() % (n-1);
                    numQ = Math.abs(numQ);
                    if(((question) list.get(numQ)).getWeightInt()<=3){
                        //changing for an harder question
                        String top =((question) list.get(numQ)).getTopic();
                        String query="SELECT QNO,TOPIC,SUBTOPIC,WT,PTS FROM SAVEQA WHERE TOPIC = '"+top+"'";
                        ResultSet rs = st.executeQuery(query);
                        count = 0;
                        while (rs.next())
                            count++;
                        while(!found){
                            rs.first();
                            int quest = random.nextInt();
                            quest = quest % (count-1);                         
                            quest = Math.abs(quest);
                            for(int aux=0; aux<quest; aux++)
                                rs.next();
                     
                            question que = new question(rs.getInt("qno"),rs.getString("topic"),rs.getString("subtopic"),rs.getString("wt"),rs.getInt("pts"));                    
                            if(!this.isQuestion(list, que.getNumQuestion())){
                                if(que.getWeightInt()>2){
                                    list.set(numQ, que);
                                    found = true;
                                }
                            }
                        }
                    }
                }
                if(harderDif<averageCounter){
                    int numQ = random.nextInt() % (n-1);
                    numQ = Math.abs(numQ);
                    if(((question) list.get(numQ)).getWeightInt()>=3){
                        //changing for an easier question
                        String top =((question) list.get(numQ)).getTopic();
                        String query="SELECT QNO,TOPIC,SUBTOPIC,WT,PTS FROM SAVEQA WHERE TOPIC = '"+top+"'";
                        ResultSet rs = st.executeQuery(query);
                        count = 0;
                        while (rs.next())
                            count++;
                        while(!found){
                            rs.first();
                            int quest = random.nextInt();
                            quest = quest % (count-1);                         
                            quest = Math.abs(quest);
                            for(int aux=0; aux<quest; aux++)
                                rs.next();
                     
                            question que = new question(rs.getInt("qno"),rs.getString("topic"),rs.getString("subtopic"),rs.getString("wt"),rs.getInt("pts"));                    
                            if(!this.isQuestion(list, que.getNumQuestion())){
                                if(que.getWeightInt()<4){
                                    list.set(numQ, que);
                                    found = true;
                                }
                            }
                        }
                    } 
                }
                counter = 0;
                for(int j=0;j<list.size();j++)
                    counter+=((question) list.get(j)).getWeightInt();
                averageCounter = (float)counter/(float)list.size();
            }
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Exception");
        } catch (SQLException ex) {
            System.out.println("Exception");
        }
        
        return list;
    }
    public boolean isSubtopic(ArrayList questions, String topic, String subtopic){
        for(int i = 0; i<questions.size();i++){
            question q = (question) questions.get(i);
            if((q.getTopic().equals(topic))&&(q.getSubtopic().equals(subtopic)))
                return true;
        }
        return false;
    }
    
    public boolean isQuestion(ArrayList questions, int numQ){
        for(int i = 0; i<questions.size();i++){
            question q = (question) questions.get(i);
            if(q.getNumQuestion()==numQ)
                return true;
        }
        return false;
    }
    
    public String topics(int pos){
        ConnectionDB conDB = new ConnectionDB();
        Connection con = conDB.createConnection(); //Creating connection
        String topic = "";
        ResultSet rs = null; 
        try {
            Statement st = con.createStatement();                  
            String query = "SELECT * FROM TOPSUB WHERE TOPIC IS NOT NULL "; 
            rs = st.executeQuery(query); 
            for(int i = 1; i<=pos;i++)
                rs.next();
            topic = rs.getString("TOPIC");            
        } catch (SQLException ex) {
            System.out.println("Impossible connection with database2");
        }
        conDB.closeConnection(con);
        return topic;
    }
    
    public String subtopics(int pos){
        ConnectionDB conDB = new ConnectionDB();
        Connection con = conDB.createConnection(); //Creating connection
        String topic = "";
        ResultSet rs = null; 
        try {
            Statement st = con.createStatement();                  
            String query = "SELECT * FROM TOPSUB WHERE SUBTOPIC IS NOT NULL "; 
            rs = st.executeQuery(query); 
            for(int i = 1; i<=pos;i++)
                rs.next();
            topic = rs.getString("SUBTOPIC");            
        } catch (SQLException ex) {
            System.out.println("Impossible connection with database2");
        }
        conDB.closeConnection(con);
        return topic;
    }
}
